package com.getword.service.impl;

import com.getword.domain.Follow;
import com.getword.domain.User;
import com.getword.mongodao.FollowRepository;
import com.getword.service.FollowService;
import com.getword.utils.SpringContextUtil;
import com.getword.web.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class FollowServiceImpl implements FollowService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FollowRepository followRepository;

    @Override
    public Result getFollowState(Long followedUserId) { // 获取关注状态
        User user = SpringContextUtil.getLoginUser();
        Follow follow = followRepository.findFollowByUserIdAndFollowedUserId(user.getId(), followedUserId);
        Boolean state = follow != null;
        return Result.success(state);
    }

    @Override
    public Result followAuthor(Long followedUserId) { // 关注
        User user = SpringContextUtil.getLoginUser();
        // 查看是否已经关注了
        Follow followed = followRepository.findFollowByUserIdAndFollowedUserId(user.getId(), followedUserId);
        if(followed != null){
            return Result.fail("已经关注了!");
        }
        Follow follow = new Follow();
        follow.setUserId(user.getId());
        follow.setFollowedUserId(followedUserId);
        follow.setFollowTime(new Date());
        Follow save = followRepository.save(follow);
        return Result.success(save);
    }

    @Override
    public Result cancelFollow(Long followedUserId) {  // 取消关注
        User user = SpringContextUtil.getLoginUser();
        // 查看是否已经关注了
        Follow followed = followRepository.findFollowByUserIdAndFollowedUserId(user.getId(), followedUserId);
        if(followed == null){
            return Result.fail("还没有关注!");
        }
        followRepository.delete(followed);
        return Result.success(true);
    }
}
